package com.lagou.servlet;

import com.lagou.factory.BeanFactory;
import com.lagou.pojo.Result;
import com.lagou.factory.ProxyFactory;
import com.lagou.service.TransferService;
import com.lagou.utils.JsonUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 应癫
 */
@WebServlet(name="transferServlet",urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

    // 1. 实例化service层对象
   /* private TransferService transferService = new TransferServiceImpl();*/

    //2.用反射实例service对象
    /*private TransferService transferService = (TransferService) BeanFactory.getBeanById("transferService") ;*/
    //3.通过代理对象获取service对象
    //3.1第一步：获取代理对象工厂
    //private ProxyFactory proxyFactory = (ProxyFactory)BeanFactory.getBeanById("proxyFactory");
    //3.2第二步：通过代理对象工厂获取service的代理类
    private TransferService transferService = null;

    @Override
    public void init() throws ServletException {
        WebApplicationContext applicationContext= WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        /*ProxyFactory proxyFactory = (ProxyFactory) applicationContext.getBean("proxyFactory");
        transferService = (TransferService) proxyFactory.getCglibProxy(applicationContext.getBean("transferService"));*/
        transferService = (TransferService) BeanFactory.getBean("transferService");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {
            WebApplicationContext applicationContext= WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
            transferService = (TransferService) BeanFactory.getBean("transferService");
            // 2. 调用service层方法
            transferService.transfer(fromCardNo,toCardNo,money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }
}
